package com.fxz.bean.utils;

import lombok.SneakyThrows;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

/**
 * 反射工具类
 *
 * @author Fxz
 * @version 1.0
 * @date 2021-08-12 16:06
 */
public class ReflectionUtils {
    /**
     * 通过Class与参数 通过构造生成实例
     *
     * @param cls
     * @param arg
     * @return
     */
    @SneakyThrows
    public static Object createObject(Class<?> cls, Object... arg) {
        Constructor<?> constructor = cls.getConstructor();
        return constructor.newInstance(arg);
    }

    /**
     * 通过反射 为是实体类的字段设置值
     *
     * @param singleton
     * @param name
     * @param valueToUse
     */
    @SneakyThrows
    public static void setProperty(Object singleton, String name, Object valueToUse) {
        Field field = singleton.getClass().getDeclaredField(name);
        field.setAccessible(true);
        field.set(singleton, valueToUse);
    }

    @SneakyThrows
    public static Class<?> getTypeByFiledName(String className, String name) {
        Class<?> aClass = Class.forName(className);
        return aClass.getDeclaredField(name).getType();
    }
}
